package com.ruoyi.law.util;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.*;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.HashMap;
import java.util.UUID;

@Getter
@Setter
@Component
public class OssUtil {
    @Autowired
    private ResourceLoader resourceLoader;
    public static OSSClient client;


    static String accessKeyId = "LTAI5tRF47fD89gnKzH2qTao";
    static String accessKeySecret= "u2qAIhiqzqbq2osxTmC1WaaiFXki26";
    static String bucketName= "txnongantong";
    static  String endpoint= "https://oss-cn-beijing.aliyuncs.com";
    static  String httpUrlPre= "https://txnongantong.oss-accelerate.aliyuncs.com/";

    public OSSClient initClient(){
        if(null==client){
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(5000);
            conf.setMaxErrorRetry(10);
            conf.setSupportCname(true);
            client = new OSSClient("http://" + endpoint, accessKeyId, accessKeySecret,conf);
        }
        return client;
    }
    /**
     * 上传文件
     *
     * @param fileKey 对应文件名称
     * @param content  文件流
     * @throws FileNotFoundException
     */
    public boolean putObjectForInputStream(String fileKey, InputStream content) {
        ClientBuilderConfiguration CONFIGURATION = new ClientBuilderConfiguration();
        CONFIGURATION.setSupportCname(true);

        // System.out.println(endpoint+" .... "+ accessKeyId+" .... "+ accessKeySecret);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret,CONFIGURATION);

        if (null == fileKey || "" == fileKey.trim())
            return false;
        try {
            initClient();
            ObjectMetadata meta = new ObjectMetadata();
            ossClient.putObject(bucketName, fileKey, content, meta);

            // 关闭OSSClient。
            ossClient.shutdown();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 上传图片
     * @param imageName 文件夹名称
     * @param if400 对应文件名称
     * @param content  文件流
     * @throws FileNotFoundException
     */
    public String putObjectForImage(String imageName, InputStream content, boolean if400) {
        if (null == imageName || "" == imageName.trim())
            return null;
        try {
            String file = "images/" + imageName.substring(0, imageName.indexOf(".")) + "/" + imageName;
            putObjectForInputStream(file,content);
            return httpUrlPre+"/"+file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public String getObject(String key) {
        try {
            OSSObject object = client.getObject(bucketName, key);
            InputStream objectContent = object.getObjectContent();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int i = -1;
            while ((i = objectContent.read()) != -1) {
                baos.write(i);
            }
            objectContent.close();
            return baos.toString("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 上传返回路径
     */
    public  String getFileUrl(String url){
        //文件流
        File file = new File(url);

        ClientBuilderConfiguration CONFIGURATION = new ClientBuilderConfiguration();
        CONFIGURATION.setSupportCname(true);

        // System.out.println(endpoint+" .... "+ accessKeyId+" .... "+ accessKeySecret);
        // 创建OSSClient实例。
//            String accessKeyId = "LTAI5t9PATGTgp6nPAaf1V4n";
//    String accessKeySecret= "tpXOSeUdKxIPZJM3PQNwCRZDVbwkj3";
//    String endpoint= "https://oss-cn-beijing.aliyuncs.com";
//    String bucketName= "nongantong";
//    String httpUrlPre= "https://www.nongantong.com/app/aio1.9.apk";
//
//
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret,CONFIGURATION);
        /*
            创建PutObjectRequest对象。
            <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
            filePath:生成路径
        */
        String filePath = getFilePath(file.getName(),"static/");
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePath,file);


        // 上传文件。
        ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();

        //返回地址
        //return endpoint+"/"+filePath;


        String dd = StringUtils.substringAfterLast(file.getName(), ".").toLowerCase();
        /**
         * 判断是否是图片
         */
        if("jpg".equals(dd) ||"jpeg".equals(dd)||"gif".equals(dd)||"bmp".equals(dd)||"png".equals(dd)||"tiff".equals(dd)||"svg".equals(dd)||"webp".equals(dd)) {
        	return httpUrlPre +filePath + "_small";
        }else {
        	return httpUrlPre+filePath;
        }


    }
    /**
     * 上传返回路径
     */
    public  HashMap<String, Object> uploadFileUrl(MultipartFile mpf) throws Exception {
        //文件流转换
        File file = multipartFileToFile(mpf);

        ClientBuilderConfiguration CONFIGURATION = new ClientBuilderConfiguration();
        CONFIGURATION.setSupportCname(true);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret,CONFIGURATION);
        /*
            创建PutObjectRequest对象。
            <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
            filePath:生成路径
        */
        String filePath = getFilePath(file.getName());
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePath,file);
        // 上传文件。
        ossClient.putObject(putObjectRequest);
        // 关闭OSSClient。
        ossClient.shutdown();
        String dd = StringUtils.substringAfterLast(file.getName(), ".").toLowerCase();
        /**
         * 判断是否是图片
         */
        HashMap<String, Object> mapResult = new HashMap<String, Object>();
        if("jpg".equals(dd) ||"jpeg".equals(dd)||"gif".equals(dd)||"bmp".equals(dd)||"png".equals(dd)||"tiff".equals(dd)||"svg".equals(dd)||"webp".equals(dd)) {
            mapResult.put("httpAddress", httpUrlPre+filePath);
            mapResult.put("httpAddressThumb", httpUrlPre +filePath + "_small");
        }else {
            mapResult.put("httpAddress", httpUrlPre +filePath);
            mapResult.put("httpAddressThumb", httpUrlPre +filePath);
        }
        return mapResult;
    }

    /**
     * 上传返回路径
     */
    public  HashMap<String, Object> uploadFileUrl(MultipartFile mpf,String filePath1) throws Exception {

        //文件流转换
        File file = multipartFileToFile(mpf);

        return uploadFileUrl(file, filePath1);
    }

    /**
     * 上传返回路径
     */
    public  HashMap<String, Object> uploadFileUrl(File file,String filePath1) throws Exception {

        ClientBuilderConfiguration CONFIGURATION = new ClientBuilderConfiguration();
        CONFIGURATION.setSupportCname(true);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret,CONFIGURATION);
        /*
            创建PutObjectRequest对象。
            <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
            filePath:生成路径
        */
        String filePath = getFilePath(file.getName(),filePath1);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePath,file);
        // 上传文件。
        ossClient.putObject(putObjectRequest);
        // 关闭OSSClient。
        ossClient.shutdown();
        String dd = StringUtils.substringAfterLast(file.getName(), ".").toLowerCase();
        /**
         * 判断是否是图片
         */
        HashMap<String, Object> mapResult = new HashMap<String, Object>();
        if("jpg".equals(dd) ||"jpeg".equals(dd)||"gif".equals(dd)||"bmp".equals(dd)||"png".equals(dd)||"tiff".equals(dd)||"svg".equals(dd)||"webp".equals(dd)) {
            mapResult.put("httpAddress", httpUrlPre+filePath);
            mapResult.put("httpAddressThumb", httpUrlPre +filePath + "_small");
        }else {
            mapResult.put("httpAddress", httpUrlPre +filePath);
        }
        return mapResult;
    }

    /**
     * 定义一个类 用于生成上传文件名称
     */
    private  String getFilePath(String sourceFileName,String filePath) {
        DateTime dateTime = new DateTime();
        return filePath + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + UUID.randomUUID()+ "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }
    private  String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "static/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + StringUtil.getUUID() + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }



    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }
    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
